package com.huluobo.document.pages

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.document.DocumentIntent
import com.huluobo.document.DocumentViewModel
import com.huluobo.document.R
import com.huluobo.document.entity.DocumentEntity
import com.huluobo.document.entity.DocumentEntityItem
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/5/27.
 *  刷新compose中的数据源有2种形式
 *  1.SnapshotStateList 它可以识别集合的内容是否发生改变,如果发生了改变,就会对应的刷新页面,减少或者增加数据,对实时数据要求不高的时候
 *  2.重新请求数据,对实时数据要求高的时候来使用
 */

@Composable
fun DocumentPage(navHostController: NavHostController, vm: DocumentViewModel = hiltViewModel()) {
    val list = remember {
        SnapshotStateList<DocumentEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //标记要删除的item的下标
    var index by remember {
        mutableStateOf(-1)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取文件列表失败:${it.msg}")
                        Log.e("TagA", "获取文件列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        if (it.type == StateType.DEFAULT) {
                            list.clear()
                            list.addAll(it.data as DocumentEntity)
                        }

                        if (it.type == StateType.DELETE) {
                            if (index != -1) {
                                ToastUtils.showLong("删除成功")
                                //根据下标删除对应的item
                                list.removeAt(index)
                            }
                        }
                    }
                }
            }
        }
        vm.sendIntent(DocumentIntent.GetDocuments)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Scaffold(
        floatingActionButton = {
            FloatingActionButton(onClick = {
                //跳转到本地文件页面
                navHostController.navigate(RoutePath.LOCAL)
            }) {
                Icon(imageVector = Icons.Default.Add, contentDescription = "")
            }
        }
    ) {
        Column(
            Modifier
                .padding(10.dp)
                .padding(it)
        ) {
            BaseTitle(title = "文件", navHostController = navHostController)
            Spacer(modifier = Modifier.height(10.dp))
            LazyColumn(content = {
                items(list) { item ->
                    DocumentItem(entityItem = item, vm) {
                        index = list.indexOf(item)
                    }
                }
            }, verticalArrangement = Arrangement.spacedBy(10.dp))
        }
    }
}

@Composable
fun DocumentItem(entityItem: DocumentEntityItem, vm: DocumentViewModel, onClick: () -> Unit) {
    var isShow by remember {
        mutableStateOf(false)
    }
    Row(
        Modifier
            .fillMaxWidth()
            .padding(5.dp)
            .clickable {
                isShow = true
                onClick()
            }) {
        Image(
            painter = painterResource(id = R.drawable.department),
            contentDescription = "",
            modifier = Modifier.size(50.dp)
        )

        Spacer(modifier = Modifier.width(10.dp))
        Column(Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceBetween) {
            Text(text = entityItem.objName, maxLines = 1, overflow = TextOverflow.Ellipsis)
            Text(text = entityItem.createTime, color = Color.LightGray, fontSize = 11.sp)
        }
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            Text(text = "确认", Modifier.clickable {
                isShow = false
                vm.sendIntent(DocumentIntent.DeleteDocument(entityItem.id))
            })
        }, title = { Text(text = "删除提醒") },
            text = {
                Text(text = "确认删除${entityItem.objName}吗?")
            })
    }
}